package com.gnrsoft.rpc.common;

import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

public class RpcDecoder extends ByteToMessageDecoder {

//	private Class<RpcResponse> genericClass;

//	public RpcDecoder(Class<RpcResponse> classz) {
//		this.genericClass = classz;
//	}

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

		if (in.readableBytes() < 4) {
			return;
		}
		in.markReaderIndex();
		int messageLength = in.readInt();

		if (messageLength < 0) {
			ctx.close();
		}

		if (in.readableBytes() < messageLength) {
			in.resetReaderIndex();
			return;
		}

		byte[] message = new byte[in.readableBytes()];
		in.readBytes(message);

		Object obj = KryoUtil.readFromByteArray(message);
		out.add(obj);
	}

}
